package com.base.cn.platform.os.service.agent.income;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.dao.agent.income.AgentIncomeInfoDao;
import com.base.cn.platform.os.entity.agent.income.AgentIncome;
import com.base.cn.platform.os.entity.agent.income.AgentIncomeInfo;
import com.base.cn.platform.os.entity.agent.settlement.AgentSettlement;
import com.base.cn.platform.os.entity.agent.user.AgentUser;
import com.base.cn.platform.os.entity.agent.user.AgentUserClient;
import com.base.cn.platform.os.service.agent.settlement.AgentSettlementBiz;
import com.base.cn.platform.os.service.agent.user.AgentUserBiz;
import com.base.cn.platform.os.service.agent.user.AgentUserClientBiz;
import com.base.cn.platform.os.service.manage.order.goods.OrderService;
import com.base.cn.platform.os.service.manage.user.user.SetUserDataService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 所有推广员收益明细Biz
 *
 * @author LIZHIPENG
 * @create 2018-05-12 上午 11:56
 */
@Service
public class AgentIncomeInfoBiz extends BaseBiz<AgentIncomeInfo, AgentIncomeInfoDao> {

    @Autowired
    private AgentIncomeBiz agentIncomeBiz;
    @Autowired
    private AgentSettlementBiz agentSettlementBiz;
    @Autowired
    private AgentUserBiz agentUserBiz;
    @Autowired
    private SetUserDataService<AgentIncomeInfo> setUserDataService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private AgentUserClientBiz agentUserClientBiz;
    /**
     * 保存推广员收益数据列表
     * @param agentIncomeInfoList 收益列表
     */
    @Transactional(rollbackFor = IllegalArgumentException.class)
    public void saveAgentIncomeInfo(List<AgentIncomeInfo> agentIncomeInfoList){
        if(ObjectUtils.isNotEmpty(agentIncomeInfoList)){
            //获取用户ID串
            String userIds = agentIncomeInfoList.stream().map(e->e.getShareKey().split("_")[1]).collect(Collectors.joining(","));
            //得到推广员用户，以用户ID为KEY
            Map<BigDecimal,AgentUser> agentUserMap = agentUserBiz.findAgentUserByUserIds(userIds);
            if(ObjectUtils.isNotEmpty(agentUserMap)){
                agentIncomeInfoList.forEach(agentIncomeInfo->{
                    //得到用户ID
                    String userId = agentIncomeInfo.getShareKey().split("_")[1];
                    AgentUser agentUser = agentUserMap.get(new BigDecimal(userId));
                    agentIncomeInfo.setAgentUser(agentUser);
                    if(agentIncomeInfo.getAgentUser().getStatus().intValue() != 3){//删除推广员状态不正常的收益数据
                        agentIncomeInfoList.remove(agentIncomeInfo);
                    }
                    agentIncomeInfo.setStatus(1);//状态：1.未结算，2.结算中，3.已结算
                    agentIncomeInfo.setUserType(1);//消费用户类型：1.普通用户，2.下线客户
                });
                if(ObjectUtils.isNotEmpty(agentIncomeInfoList)){
                    //转成Map，推广员为KEY
                    Map<Integer,List<AgentIncomeInfo>> agentUserAgentIncomeInfoMap = agentIncomeInfoList.stream().collect(Collectors.groupingBy(e->e.getAgentUser().getUserType()));
                    List<AgentIncomeInfo> agentIncomeInfo1 = agentUserAgentIncomeInfoMap.get(1);//获取一级推广员
                    List<AgentIncomeInfo> agentIncomeInfo2 = agentUserAgentIncomeInfoMap.get(2);//获取二级推广员
                    List<AgentIncomeInfo> allList = new ArrayList<>();
                    if(ObjectUtils.isNotEmpty(agentIncomeInfo2)){//获取二级推广员的上级
                        List<AgentIncomeInfo> parentAgentIncomeInfoList = new ArrayList<>();
                        String parentIds = agentIncomeInfo2.stream().map(e->e.getAgentUser().getParentId().toString()).collect(Collectors.joining(","));
                        Map<BigDecimal,AgentUser> agentUserMap1 = agentUserBiz.findAgentUserByIds(parentIds);
                        agentIncomeInfo2.forEach(e->{
                            AgentIncomeInfo agentIncomeInfo = new AgentIncomeInfo();
                            agentIncomeInfo.setUserId(e.getUserId());//用户ID
                            agentIncomeInfo.setOrderId(e.getOrderId());//订单ID
                            agentIncomeInfo.setOrderNo(e.getOrderNo());//订单号
                            agentIncomeInfo.setDetailsId(e.getDetailsId());//流水ID
                            agentIncomeInfo.setPayTime(e.getPayTime());//支付时间
                            agentIncomeInfo.setShopData(e.getShopData());//商品数据，如1-COURSE-1
                            agentIncomeInfo.setOrderPrice(e.getOrderPrice());//订单金额
                            agentIncomeInfo.setShopPrice(e.getShopPrice());//要分成的商品价格
                            agentIncomeInfo.setShareKey(e.getShareKey());//推广员KEY
                            agentIncomeInfo.setIncomeType(2);//收益类型：1.推广收益， 2.奖励金收益
                            agentIncomeInfo.setStatus(1);//状态：1.未结算，2.结算中，3.已结算
                            agentIncomeInfo.setUserType(1);
                            AgentUser parent = agentUserMap1.get(e.getAgentUser().getParentId());
                            if(ObjectUtils.isNotEmpty(parent)){
                                agentIncomeInfo.setAgentUser(agentUserMap1.get(e.getAgentUser().getParentId()));
                                parentAgentIncomeInfoList.add(agentIncomeInfo);
                            }
                        });
                        if(ObjectUtils.isNotEmpty(parentAgentIncomeInfoList)){
                            allList.addAll(parentAgentIncomeInfoList);
                        }
                    }
                    if(ObjectUtils.isNotEmpty(agentIncomeInfo1)){
                        allList.addAll(agentIncomeInfo1);
                    }
                    if(ObjectUtils.isNotEmpty(agentIncomeInfo2)){
                        allList.addAll(agentIncomeInfo2);
                    }

                    if(ObjectUtils.isNotEmpty(allList)){
                        allList.forEach(e->{
                            AgentUser agentUser = e.getAgentUser();
                            if(agentUser.getUserType().intValue()==1){//一级推广员
                                if(e.getIncomeType().intValue()==1){//推广收益
                                    double d = e.getShopPrice().doubleValue() * (new Double(agentUser.getOneScale()) / 100D);
                                    e.setIncomePrice(d);
                                }else{//奖金收益
                                    double d = e.getShopPrice().doubleValue() * (new Double(agentUser.getBonusScale()) / 100D);
                                    e.setBonusPrice(d);
                                }
                            }
                            if(agentUser.getUserType().intValue()==2){//二级推广员
                                double d = e.getShopPrice().doubleValue() * (new Double(agentUser.getTwoScale()) / 100D);
                                e.setIncomePrice(d);
                            }
                            e.setAgentUserId(agentUser.getId());
                        });
                        this.batchSave(allList);
                        agentIncomeBiz.updateAgentIncomeData(allList);
                        AgentIncomeInfo incomeInfo = allList.get(0);
                        incomeInfo.getAgentUser().getId();
                        AgentUserClient client = new AgentUserClient();
                        client.setUserId(incomeInfo.getUserId());
                        client.setAgentId(incomeInfo.getAgentUser().getId());
                        agentUserClientBiz.saveAgentUserClient(client);
                    }
                }
            }
        }
    }

    /**
     * 查询收益明细列表（分页）
     * @param page 分页
     * @param agentIncomeInfo 查询条件
     * @param userData 是否设置用户信息
     * @param shopData 是否设置商品信息
     * @return PageInfo<AgentIncomeInfo>
     */
    public PageInfo<AgentIncomeInfo> queryIncomeInfoListPage(Pagination page, AgentIncomeInfo agentIncomeInfo, boolean userData, boolean shopData) {
        agentIncomeInfo.setShopData(getOrderIdSql(agentIncomeInfo));
        String whereSql = getWhereSql(agentIncomeInfo);
        PageInfo<AgentIncomeInfo> agentIncomeInfoPageInfo = this.findPage(whereSql, page, null);
        agentIncomeInfoPageInfo.setList(this.setExtendData(agentIncomeInfoPageInfo.getList(), userData, shopData));
        return agentIncomeInfoPageInfo;
    }

    /**
     * 查询收益明细列表（不分页）
     * @param agentIncomeInfo 查询条件
     * @param userData 是否设置用户信息
     * @param shopData 是否设置商品信息
     * @return List<AgentIncomeInfo>
     */
    public List<AgentIncomeInfo> queryIncomeInfoList(AgentIncomeInfo agentIncomeInfo, boolean userData, boolean shopData){
        String whereSql = getWhereSql(agentIncomeInfo);
        List<AgentIncomeInfo> agentIncomeInfoList = this.find(whereSql, agentIncomeInfo.getCount(), null);
        return this.setExtendData(agentIncomeInfoList, userData, shopData);
    }

    /**
     * 查询推广员的可结算收益列表
     * @param agentUser 推广员
     * @return Map<String, Object>
     */
    public Map<String, Object> queryIsAvailableIncome(AgentUser agentUser){
        if(ObjectUtils.isNotEmpty(agentUser) && DataUtil.idIsNotNull(agentUser.getId())){
            Map<String, Object> map = new HashMap<>();
            AgentIncome agentIncome = agentUser.getAgentIncome();
            if(ObjectUtils.isEmpty(agentIncome)){
                agentIncome = agentIncomeBiz.findAgentIncomeById(agentUser.getId(), false);
            }
            //查询收益明细的开始时间
            Date beginTime = agentUser.getCreateTime();
            if(agentIncome.getCycleNum()>0){//之前结算过
                AgentSettlement agentSettlement = new AgentSettlement();
                agentSettlement.setAgentUserId(agentUser.getId());
                agentSettlement.setCycleNum(agentIncome.getCycleNum());
                List<AgentSettlement> agentSettlements = agentSettlementBiz.querySettlementList(agentSettlement, false);
                if(ObjectUtils.isNotEmpty(agentSettlements)){
                    beginTime = agentSettlements.get(0).getEndTime();
                }
            }
            //当前系统时间
            Date currentTime = new Date();
            String[] currentDateArr = DateUtils.format(currentTime, "yyyy-MM-dd").split("-");
            String[] beginDateArr = DateUtils.format(beginTime, "yyyy-MM-dd").split("-");

            AgentIncomeInfo agentIncomeInfo = new AgentIncomeInfo();
            agentIncomeInfo.setAgentUserId(agentUser.getId());
            agentIncomeInfo.setStatus(1);
            agentIncomeInfo.setStartTime(DateUtils.format(beginTime, "yyyy-MM-dd HH:mm:ss"));
            if(agentUser.getSettType() == 1){//随时结
                agentIncomeInfo.setEndTime(DateUtils.format(currentTime, "yyyy-MM-dd HH:mm:ss"));
            }else if(agentUser.getSettType() == 2){//月结
                agentIncomeInfo.setEndTime(currentDateArr[0] + "-" + currentDateArr[1] + "-01 00:00:00");
            }else {
                agentIncomeInfo.setEndTime(currentDateArr[0] + "-01-01 00:00:00");
            }
            List<AgentIncomeInfo> incomeInfos = this.queryIncomeInfoList(agentIncomeInfo, false, false);
            map.put("beginTime", beginTime);
            map.put("currentTime", currentTime);
            map.put("beginDateArr", beginDateArr);
            map.put("currentDateArr", currentDateArr);
            map.put("incomeInfos", incomeInfos);
            return map;
        }
        return Collections.emptyMap();
    }

    //=====================================================
    private String getWhereSql(AgentIncomeInfo agentIncomeInfo){
        String whereSql = "1=1";
        if(ObjectUtils.isNotEmpty(agentIncomeInfo)){
            if(DataUtil.idIsNotNull(agentIncomeInfo.getId())){
                whereSql += " and id="+ agentIncomeInfo.getId();
            }
            if(DataUtil.idIsNotNull(agentIncomeInfo.getAgentUserId())){
                whereSql += " and agentUserId="+ agentIncomeInfo.getAgentUserId();
            }
            if (DataUtil.idIsNotNull(agentIncomeInfo.getSettlementId())) {
                whereSql += " and settlementId="+ agentIncomeInfo.getSettlementId();
            }
            if(StringUtils.isNotEmpty(agentIncomeInfo.getBeginPayTime())){
                whereSql += " and createTime>='"+ agentIncomeInfo.getBeginPayTime() +"'";
            }
            if(StringUtils.isNotEmpty(agentIncomeInfo.getEndPayTime())){
                whereSql += " and createTime<='"+ agentIncomeInfo.getEndPayTime() +"'";
            }
            if(StringUtils.isNotEmpty(agentIncomeInfo.getStartTime())){
                whereSql += " and createTime>='"+ agentIncomeInfo.getStartTime() +"'";
            }
            if(StringUtils.isNotEmpty(agentIncomeInfo.getEndTime())){
                whereSql += " and createTime<'"+ agentIncomeInfo.getEndTime() +"'";
            }
            if(ObjectUtils.isNotEmpty(agentIncomeInfo.getIncomeType())){
                whereSql += " and incomeType="+ agentIncomeInfo.getIncomeType();
            }
            if (StringUtils.isNotEmpty(agentIncomeInfo.getShopData())){
                whereSql += " and orderId in "+ agentIncomeInfo.getShopData().trim() ;
            }
            if(ObjectUtils.isNotEmpty(agentIncomeInfo.getStatus())){
                whereSql += " and status = "+ agentIncomeInfo.getStatus();
            }
        }
        whereSql += " order by id desc";
        return whereSql;
    }

    //设置扩展数据
    private List<AgentIncomeInfo> setExtendData(List<AgentIncomeInfo> agentIncomeInfoList, boolean userData, boolean shopData){
        if(userData){
            agentIncomeInfoList = setUserData(agentIncomeInfoList, userData);
        }
        if(shopData){
            agentIncomeInfoList = setShopData(agentIncomeInfoList, shopData);
        }
        return agentIncomeInfoList;
    }

    //设置用户数据
    private List<AgentIncomeInfo> setUserData(List<AgentIncomeInfo> agentIncomeInfoList, boolean userData){
        return setUserDataService.setUserData(agentIncomeInfoList, userData);
    }

    //设置商品数据
    private List<AgentIncomeInfo> setShopData(List<AgentIncomeInfo> agentIncomeInfoList, boolean shopData){
        if(ObjectUtils.isNotEmpty(agentIncomeInfoList) && shopData){
            String orderIds = agentIncomeInfoList.stream().map(e -> e.getOrderId().toString()).distinct().collect(Collectors.joining(","));
            Map<String, Object> condition = new HashMap<>();
            condition.put("ids", orderIds);
            List<Map<String, Object>> orderList = orderService.findOrderList(condition, false, true, true, false);
            if(ObjectUtils.isNotEmpty(orderList)){
                for (AgentIncomeInfo incomeInfo : agentIncomeInfoList) {
                    for (Map<String, Object> map : orderList) {
                        BigDecimal orderId = new BigDecimal((Integer)map.get("id"));
                        if(orderId.equals(incomeInfo.getOrderId())){
                            incomeInfo.setOrder(map);
                            break;
                        }
                    }
                }
            }
        }
        return agentIncomeInfoList;
    }

    //
    public String getOrderIdSql(AgentIncomeInfo agentIncomeInfo){
        Object shopNames = agentIncomeInfo.getShopData();
        if(ObjectUtils.isNotEmpty(shopNames)){
            Map<String,Object> params = new HashMap<>();
            params.put("shopNames",shopNames);
            List<Map<String,Object>> orderList = orderService.findOrderList(params,false,false,true,false);
            String sql = "";
            for(int i=0 ;i<orderList.size();i++){
                sql += orderList.get(i).get("id").toString()+",";
            }
            sql = StringUtils.subHeadTailString(sql,",");
            if(StringUtils.isNotEmpty(sql))
                sql = "("+sql+")";
            else
                sql = "(-1)";
            return sql;
        }
        return null;
    }
}
